package com.zhx.ad.common.advice;

import com.zhx.ad.common.annotation.IgnoreResponseAdvice;
import com.zhx.ad.common.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *describe: 
 *
 *@author zhanghaixuan
 *@date 2019/02/01
 **/
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

	/**
	 * 判断响应是否去拦截
	 * @param methodParameter 方法的参数
	 * @param aClass
	 * @return boolean
	 */
	@Override
	@SuppressWarnings("all")
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		// 判断是否有这个注解  有就不管了  类上有
		if(methodParameter.getAnnotatedElement().isAnnotationPresent(IgnoreResponseAdvice.class)) {
			return false;
		}
		// 判断是否有这个注解  有就不管了  方法上有
		if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
			return false;
		}

		return true;
	}

	/**
	 * 对返回的结果进行处理
	 * @param o 结果
	 * @param methodParameter 参数
	 * @param mediaType 类型
	 * @param aClass
	 * @param serverHttpRequest 请求
	 * @param serverHttpResponse 结果
	 * @return Object
	 */
	@Override
	@Nullable
	@SuppressWarnings("all")
	public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter, MediaType mediaType,
			Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
			ServerHttpResponse serverHttpResponse) {
		CommonResponse<Object> commonResponse = new CommonResponse(0,"");

		if(null == o){
			return o;
		}else if(o instanceof CommonResponse){
			commonResponse= (CommonResponse<Object>) o;
		}else{
			commonResponse.setData(o);
		}

		return commonResponse;
	}
}
